package com.voicechat.firstmet.imcontrol;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGADynamicEntity;
import com.opensource.svgaplayer.SVGAImageView;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;
import com.tencent.TIMCustomElem;
import com.tencent.TIMMessage;
import com.voicechat.firstmet.App;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.IMChatActivity;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 自定义消息
 */
public class CustomMessage extends Message implements Parcelable{
    private String type;//消息类型 4礼物 6搭讪 7通话结束
    private String TAG = "CustomMessage";
    private String desc;
    private String data;//消息数据
    private String giftName;//礼物名称
    private String giftId;//礼物id
    private String giftNumber;//礼物数量
    private String imgUrl;//礼物地址
    private String animationUrl;//礼物动画地址
    private String gold;//金币余额
    private String accost;//搭讪文本
    private String duration;//通话时间


    protected CustomMessage(Parcel in) {
        type = in.readString();
        TAG = in.readString();
        desc = in.readString();
        data = in.readString();
    }
    public static final Creator<CustomMessage> CREATOR = new Creator<CustomMessage>() {
        @Override
        public CustomMessage createFromParcel(Parcel in) {
            return new CustomMessage(in);
        }

        @Override
        public CustomMessage[] newArray(int size) {
            return new CustomMessage[size];
        }
    };

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }


    public CustomMessage(TIMMessage message){
        this.message = message;
        TIMCustomElem elem = (TIMCustomElem) message.getElement(0);
        //Log.i(TAG, "CustomMessage: -----------");
        parse(elem.getExt());
    }
    public CustomMessage(String type,String roomId,String price){
        message = new TIMMessage();
        String data = "";
        JSONObject dataJson = new JSONObject();
        TIMCustomElem elem = new TIMCustomElem();
        elem.setData(data.getBytes());
        message.addElement(elem);
    }
    /**
    * @method
    * @description 收到的消息解析
    * @date: 2018/11/12 19:29
    * @author: ljp
    * @return
    */
    private void parse(byte[] data){
        try {
            String str = new String(data, "UTF-8");
            String[] strings = Utils.spitPictureUrl(str);
            Log.i(TAG, "parse: ----ext-----"+str);
            for (int i = 0;i< strings.length;i++){
                String[] object = Utils.spitInfo(strings[i], ":");
                if(object.length != 0 && object.length != 1) {
                    switch (object[0]) {
                        case "type":
                            if(!TextUtils.isEmpty(object[1]) && !object[1].equals("null")) {
                                type = object[1];
                            }
                            break;
                        case "giftName":
                            if(!TextUtils.isEmpty(object[1])) {
                                giftName = object[1];
                            }
                            break;
                        case "giftId":
                            if (object[1] != null) {
                                giftId = object[1];
                            }
                            break;
                        case "giftNumber":
                            if(!TextUtils.isEmpty(object[1])) {
                                giftNumber = object[1];
                            }
                            break;
                        case "imgUrl":
                            if(!TextUtils.isEmpty(object[1])) {
                                imgUrl = object[1];
                            }
                            break;
                        case "animationUrl":
                            if (!TextUtils.isEmpty(object[1]) && object[1].contains("/")) {
                                animationUrl = object[1];
                            }
                            break;
                        case "gold":
                            if (object[1] != null) {
                                gold = object[1];
                            }
                            break;
                        case "accost":
                            if (object[1] != null) {
                                accost = object[1];
                            }
                            break;
                        case "duration":
                            if (object[1] != null) {
                                duration = object[1];
                            }
                            break;
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    /**
     * 显示消息
     *
     * @param viewHolder 界面样式
     * @param context    显示消息的上下文
     */
    @Override
    public void showMessage(ChatAdapter.ViewHolder viewHolder, Context context) {
        clearView(viewHolder);
        Log.i(TAG, "showMessage: ---------");
        viewHolder.rightAccount.setVisibility(View.GONE);
        View giftView = null;
        if(type.equals(Type.CustomMsgVoiceChatEnd7)){//语音通话结束页面
            giftView = View.inflate(context, R.layout.item_voice_custom_message, null);
            //自己的显示界面
            RelativeLayout relaRightVoice = giftView.findViewById(R.id.rela_right_voice_message);
            TextView tvVoiceTextRight = giftView.findViewById(R.id.tv_voice_time);
            //对方的显示界面
            RelativeLayout relaLeftVoice = giftView.findViewById(R.id.rela_left_voice_message);
            TextView tvVoiceTextLeft = giftView.findViewById(R.id.tv_voice_time_left);
            if (isSelf()){
                relaRightVoice.setVisibility(View.VISIBLE);
                if(duration != null) {
                    tvVoiceTextRight.setText("通话时长 " + Utils.getFormatHMS(Integer.parseInt(duration) * 1000));
                }
            }else {
                relaLeftVoice.setVisibility(View.VISIBLE);
                if(duration != null) {
                    tvVoiceTextLeft.setText("通话时长 " + Utils.getFormatHMS(Integer.parseInt(duration) * 1000));
                }
            }
        }else {//礼物 搭讪页面
            giftView = View.inflate(context, R.layout.item_gift_custom_message, null);
            //自己的显示界面
            RelativeLayout relaRightGift = giftView.findViewById(R.id.rela_right_gift_message);
            ImageView rightGiftIcon = giftView.findViewById(R.id.image_gift_icon);
            TextView tvGiftTextRight = giftView.findViewById(R.id.tv_gift_text);
            TextView tvGiftNameRight = giftView.findViewById(R.id.tv_right_gift_name);
            //对方的显示界面
            RelativeLayout relaLeftGift = giftView.findViewById(R.id.rela_left_gift_message);
            ImageView leftGiftIcon = giftView.findViewById(R.id.image_gift_icon_left);
            TextView tvGiftTextLeft = giftView.findViewById(R.id.tv_gift_text_left);
            TextView tvGiftNameLeft = giftView.findViewById(R.id.tv_left_gift_name);
            if (isSelf()) {
                relaRightGift.setVisibility(View.VISIBLE);
                GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP + imgUrl,
                        rightGiftIcon);
                if (type.equals(Type.CustomMsgGif4)) {
                    tvGiftTextRight.setText("礼物");
                } else if (type.equals(Type.CustomMsgGif6)) {
                    tvGiftTextRight.setText("搭讪礼物");
                    viewHolder.rightAccount.setVisibility(View.VISIBLE);
                    viewHolder.rightAccount.setBackgroundResource(R.drawable.layout_backgroup);
                    viewHolder.rightAccountText.setText(accost);
                }
                tvGiftNameRight.setText(giftName + "x" + giftNumber);
            } else {
                relaLeftGift.setVisibility(View.VISIBLE);
                GlideLoadUtils.getInstance().glideLoad(App.getContext(), OssConfig.OSS_HTTP + imgUrl,
                        leftGiftIcon);
                if (type.equals(Type.CustomMsgGif4)) {
                    tvGiftTextLeft.setText("礼物");
                } else {
                    tvGiftTextLeft.setText("搭讪礼物");
                }
                tvGiftNameLeft.setText(giftName + "x" + giftNumber);
                if (!TextUtils.isEmpty(animationUrl)) {
                    Log.i(TAG, "showMessage: ---isRead-----" + isRead());
                    Log.i(TAG, "showMessage: ----animationUrl----" + animationUrl);
                    if (!isRead()) {
                        //播放动画
                        try {
                            showPopu(new URL(OssConfig.OSS_HTTP + animationUrl), context);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }
                        //设为已读
                        message.getConversation().setReadMessage();
                    }
                }
            }
            long timestamp = message.timestamp();
            //Log.i(TAG, "showMessage: ----transformTime-----"+Utils.formatUnixTime(timestamp,"yyyy-MM-dd HH:mm:ss"));
        }
        getBubbleView(viewHolder).addView(giftView);
        showStatus(viewHolder);
    }
    private void showPopu(URL url,Context context) {
        View view = View.inflate(context,R.layout.popu_ceishi,null);
        SVGAImageView svgImage = view.findViewById(R.id.svgImage);
        PopUtils.showPopupWindowURL((IMChatActivity) context,view,false);
        loadAnimation(url,context,svgImage);
    }
    /**
     * @method
     * @description 送礼物动画
     * @date: 2018/11/23 11:49
     * @author: ljp
     * @return
     */
    public  void loadAnimation(URL url,Context context,SVGAImageView svgaImageView) {
        SVGAParser parser = new SVGAParser(context);
        resetDownloader(parser);
        parser.parse(url, new SVGAParser.ParseCompletion() {
            @Override
            public void onComplete(@NotNull SVGAVideoEntity videoItem) {
                SVGADrawable drawable = new SVGADrawable(videoItem, requestDynamicItemWithSpannableText());
                svgaImageView.setVisibility(View.VISIBLE);
                svgaImageView.setImageDrawable(drawable);
                svgaImageView.setLoops(1);
                svgaImageView.startAnimation();
            }
            @Override
            public void onError() {
            }
        });
        svgaImageView.setCallback(new SVGACallback() {
            @Override
            public void onPause() {
            }
            @Override
            public void onFinished() {
                if(PopUtils.isPopShowing()){
                    PopUtils.hidePopupWindow();
                }
                //svgaImageView.setVisibility(View.GONE);
            }
            @Override
            public void onRepeat() {
            }
            @Override
            public void onStep(int frame, double percentage) {
            }
        });
    }
    /**
     * 你可以设置富文本到 ImageKey 相关的元素上
     * 富文本是会自动换行的，不要设置过长的文本
     *
     * @return
     */
    private SVGADynamicEntity requestDynamicItemWithSpannableText() {
        SVGADynamicEntity dynamicEntity = new SVGADynamicEntity();
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("Pony 送了一打风油精给主播");
        spannableStringBuilder.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        TextPaint textPaint = new TextPaint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(28);
        dynamicEntity.setDynamicText(new StaticLayout(
                spannableStringBuilder,
                0,
                spannableStringBuilder.length(),
                textPaint,
                0,
                Layout.Alignment.ALIGN_CENTER,
                1.0f,
                0.0f,
                false
        ), "banner");
        dynamicEntity.setDynamicDrawer(new Function2<Canvas, Integer, Boolean>() {
            @Override
            public Boolean invoke(Canvas canvas, Integer frameIndex) {
                Paint aPaint = new Paint();
                aPaint.setColor(Color.WHITE);
                canvas.drawCircle(50, 54, frameIndex % 5, aPaint);
                return false;
            }
        }, "banner");
        return dynamicEntity;
    }

    /**
     * 设置下载器，这是一个可选的配置项。
     *
     * @param parser
     */
    private void resetDownloader(SVGAParser parser) {
        parser.setFileDownloader(new SVGAParser.FileDownloader() {
            @Override
            public void resume(final URL url, final Function1<? super InputStream, Unit> complete, final Function1<? super Exception, Unit> failure) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder().url(url).get().build();
                        try {
                            Response response = client.newCall(request).execute();
                            complete.invoke(response.body().byteStream());
                        } catch (IOException e) {
                            e.printStackTrace();
                            failure.invoke(e);
                        }
                    }
                }).start();
            }
        });
    }

    /**
     * 获取消息摘要
     */
    @Override
    public String getSummary() {
        String summary = "";
        if (type != null){
            if (type.equals(Type.CustomMsgGif6)) {
                summary = App.getInstance().getApplicationContext().getString(R.string.summary_account_gif);
            } else if ((type.equals(Type.CustomMsgGif4))) {
                summary = App.getInstance().getApplicationContext().getString(R.string.summary_gif);
            } else if ((type.equals(Type.CustomMsgVoiceChatEnd7))) {
                summary = App.getInstance().getApplicationContext().getString(R.string.summary_voice_chat);
            }
    }
        return summary;
    }

    /**
     * 保存消息或消息文件
     */
    @Override
    public void save() {

    }
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(type);
        dest.writeString(TAG);
        dest.writeString(desc);
        dest.writeString(data);
    }

    public interface Type{
        String CustomMsgGif4 = "4";//聊天发送礼物
        String CustomMsgGif6 = "6";//搭讪礼物
        String CustomMsgVoiceChatEnd7 = "7";//语音聊天结束
    }
}
